﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;

namespace X13.Player
{
    public sealed class PlayerHUB
    {
        public static readonly int StartCash = 1000;

        //Fields
        private List<PlayerProfile> _PlayerData;
        private int _LoggedInIndex = -1;

        public PlayerProfile LoggedInPlayer
        { 
            get
            {
                if (_LoggedInIndex == -1)
                    throw new X13FrameworkError(Errors.LoggedInPlayerNotSet);

                return _PlayerData[_LoggedInIndex]; 
            }
        }
        public IEnumerable<PlayerProfile> Profiles { get { return _PlayerData; } }

        //cTor
        public PlayerHUB()
        {
            _PlayerData = new List<PlayerProfile>();
        }

        //Methods
        public void AddPlayer(PlayerProfile data)
        {
            data.AddCurrency(StartCash);
            _PlayerData.Add(data);
        }
        public void Clear()
        {
            _PlayerData = new List<PlayerProfile>();
        }

        public bool IsEmpty() { return _PlayerData.Count == 0; }
        
        public void Serialize()
        {
            Stream fs = File.Open(ObjectHolder.ParentGame.Content.RootDirectory + @"\data\$userdata.dat", FileMode.OpenOrCreate);
            BinaryFormatter bf = new BinaryFormatter();

            bf.Serialize(fs, _PlayerData);
            fs.Close();
        }
        public void Deserialize()
        {
            Stream fs = File.Open(ObjectHolder.ParentGame.Content.RootDirectory + @"\data\$Userdata.dat", FileMode.Open);
            BinaryFormatter bf = new BinaryFormatter();

            _PlayerData = (List<PlayerProfile>)bf.Deserialize(fs);
            fs.Close();
        }
    }
}
